"""
    led灯
"""
from fastapi import APIRouter, FastAPI, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field

import board
import digitalio


class LED:
    def __init__(self, pin):
        self.led = digitalio.DigitalInOut(pin)
        self.led.direction = digitalio.Direction.OUTPUT
        self.led.value = False

    def write(self, value):
        self.led.value = value

    def deinit(self):
        self.led.value = False
        self.led.deinit()


router = APIRouter(
    prefix='/led',
    tags=['led']
)


ledDict = {
    'yellow': board.GPIO36,
    'red': board.GPIO37,
    'green': board.GPIO38,
    'blue': board.GPIO40,
}


class LEDSchema(BaseModel):
    status: bool = Field(..., description="LED状态，true为打开，false为关闭")
    led: str = Field(..., description='led灯颜色: blue, red, yellow, green')


@router.post("/", summary='led控制')
def led_control(data: LEDSchema):
    if data.led not in ledDict:
        message = '错误的led'
        return JSONResponse(status_code=400, content={'message': message})

    obj = LED(ledDict[data.led])
    if data.status:
        obj.write(data.status)
    else:
        obj.deinit()

    return {'message': 'led控制成功'}
